﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HinduShop.DbClassLib;
using HinduShop.Domain.Models;
using HinduShop.UI.ViewModels.Cart;

namespace HinduShop.UI.Controllers
{
    public class CartController : Controller
    {
        private readonly IRepository<Product> productRepository;
        private readonly IOrderProcessor orderProcessor;

        private readonly IUnitOfWorkFactory unitOfWorkFactory;

        public CartController(
            IRepository<Product> productRepositoryParam,
            IUnitOfWorkFactory unitOfWorkFactoryParam)
        {
            productRepository = productRepositoryParam;
            unitOfWorkFactory = unitOfWorkFactoryParam;

            var emailSettings = new EmailSettings
            {
                WriteAsFile
                = bool.Parse(ConfigurationManager.AppSettings["Email.WriteAsFile"] ?? "false")
            };
            orderProcessor = new EmailOrderProcessor(emailSettings);
        }

        //
        // GET: /Cart/

        public ViewResult Index(Cart cart, string returnUrl) // cart: Custom model binder : Freeman, p. 219
        {
            return View(new CartIndexViewModel
                            {
                                Cart = cart,
                                ReturnUrl = returnUrl
                            });
        }

        public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl) // cart: Custom model binder : Freeman, p. 219
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                Product product = productRepository.ReadById(productId);

                if (product != null)
                {
                    cart.AddItem(product, 1);
                }

                uow.TransactionalFlush();

                return RedirectToAction("Index", new { returnUrl });
            }
        }

        public RedirectToRouteResult RemoveFromCart(Cart cart, int productId, string returnUrl) // cart: Custom model binder : Freeman, p. 219
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                Product product = productRepository.ReadById(productId);

                if (product != null)
                {
                    cart.RemoveLine(product);
                }
                uow.TransactionalFlush();
                return RedirectToAction("Index", new { returnUrl });
            }
        }
        
        public ViewResult Summary(Cart cart)
        {
            var model = new CartSummaryViewModel(cart);
            return View(model);
        }

        private Cart GetCart()
        {
            Cart cart = (Cart)Session["Cart"];
            if (cart == null)
            {
                cart = new Cart();
                Session["Cart"] = cart;
            }
            return cart;
        }

        #region Левые методы

        //
        // GET: /Cart/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Cart/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Cart/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Cart/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Cart/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Cart/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Cart/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        #endregion

        [HttpPost]
        public ViewResult Checkout(Cart cart, ShippingDetails shippingDetails)
        {
            if (cart.Lines.Count() == 0)
            {
                ModelState.AddModelError("", "Sorry, your cart is empty!");
            }
            if (ModelState.IsValid)
            {
                orderProcessor.ProcessOrder(cart, shippingDetails);
                cart.Clear();
                return View("Completed");
            }
            else
            {
                return View(shippingDetails);
            }
        }

        public ActionResult Checkout()
        {
            return View(new ShippingDetails());
        }
    }
}
